// pages/eventPageDetails/index.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.conmmand
const util = require('../../utils/time');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    collectId: "",
    isCollect: false,
    collectWord: '未收藏',
    activityList: null,
    articleid: 0,
    clientHeight: 557, // scroll-view 高度
    time: 1,
    id: '', //跳转聊天页面查询到的_id
    touxiang: `cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/orderimg/2022/06/30 18:44:03-200138.png`,
    userInfo: null,
    signUserList: [] // 报名人信息
  },
  doCollect() {
    // console.log(this.data.activityList)
    // console.log('活动id和用户id', this.data.activityList._id, app.globalData.userId);
    if (this.data.isCollect == false) {
      db.collection('collect').add({
        data: {
          activityId: this.data.activityList._id,
          userId: app.globalData.userId,
          status: this.data.activityList.status,
        }
      }).then(res => {
        console.log('添加成功', res)
        this.setData({
          collectWord: '已收藏',
          isCollect: true,
        })
      }).catch(err => {
        console.log('添加失败', err)
      })
    } //收藏功能完成，下面是取消收藏功能
    else {
      // console.log('先查询收藏表的_id')
      db.collection('collect').where({
        activityId: this.data.activityList._id,
        userId: app.globalData.userId,
      }).get().then(res => {
        console.log('collect集合里面查询id成功', res);
        if (res.data.length != 0) {
          console.log('查到了', res)
          this.setData({
            collectId: res.data[0]._id,
            isCollect: true,
            collectWord: "已收藏"
          })
        } else {
          console.log('未查到')
          this.setData({
            collectId: "",
            isCollect: false,
            collectWord: "未收藏"
          })
        }
        console.log('收藏表id：', this.data.collectId)
        this.delCollect(this.data.collectId)
      }).catch(err => {
        console.log('collect集合里面查询id失败', err);
      })
    }
  },
  delCollect(str) {
    console.log('开始删除的收藏表_id：', str)
    wx.cloud.callFunction({
      name: "volunteer",
      data: {
        type: "cancelCollect",
        _id: str
      }
    }).then(res => {
      console.log('云函数删除成功', res)
      this.setData({
        collectId: "",
        isCollect: false,
        collectWord: "未收藏"
      })
    }).catch(err => {
      console.log('云函数删除失败', err)
    })
  },
  btnChat(event) {
    // 带参数_id跳转
    const db = wx.cloud.database()
    var that = this
    console.log(that.data.activityList.name)
    db.collection('user').where({
      name: that.data.activityList.name
    }).get({
      success: function (res) {
        that.data.id = res.data[0]._id
        wx.navigateTo({
          url: '/pages/chat/index?_id=' + that.data.id
        })
      }
    })

  },

  onRunApi() {
    // const mapCtx = wx.createMapContext('map', this);
    // mapCtx.openMapApp({
    //     latitude: this.data.latitude,
    //     longitude: this.data.longitude,
    //     destination: this.data.name
    // })
    // 使用微信内置地图查看位置
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: (res) => {
        wx.openLocation({
          latitude: this.data.activityList.location.latitude, //目的地的纬度
          longitude: this.data.activityList.location.longitude, //目的地的经度
          name: this.data.activityList.location.name, //打开后显示的地址名称
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('articleid=', options)
    console.log('userinfo', app.globalData.userinfo._id)
    this.setData({
      articleid: options.articleid
    })
    let that = this;
    // 动态获取scroll-view 高度
    wx.getSystemInfo({
      success: function (res) {
        let screenHeight = wx.getSystemInfoSync().windowHeight
        // console.log(screenHeight)
        let query = wx.createSelectorQuery().in(that);
        query.select('.footer_button').boundingClientRect();
        query.select('.head').boundingClientRect();
        query.exec(res => {
          // console.log(res)
          let h = res[0].height;
          let h1 = res[1].height;
          // console.log(screenHeight - h - h1)
          that.setData({
            clientHeight: screenHeight - h - h1
          })
        })
      }
    })
    // 加载中
    wx.showLoading({
      title: '加载中',
    })


    // 获取报名人信息
    wx.cloud.callFunction({
      name: 'volunteer',
      data: {
        type: 'signPeopleMess',
        articleid: this.data.articleid
      }
    }).then((resp) => {
      console.log('报名人信息', resp.result.list)
      let userList = []
      let list = resp.result.list
      let index = 0
      list.forEach(element => {
        element.user[0].signTime = element.time
        userList.push(element.user[0])
      });
      console.log('baoming', userList)
      that.setData({
        signUserList: userList
      })
    })


    // 设置缓存 
    wx.getStorage({
      key: 'getActivity_' + that.data.articleid,
      success: function (res) {
        console.log('缓存的数据', res.data)
        let day = 1
        if (res.data.date != undefined) {
          let start = new Date().toISOString().substring(0, 10)
          let end = res.data.date
          let start_num = new Date(start.replace(/-/g, "/"))
          let end_num = new Date(end.replace(/-/g, "/"))
          day = parseInt((end_num.getTime() - start_num.getTime()) / (1000 * 60 * 60 * 24))
        }
        console.log('相差天数', day)
        that.setData({
          activityList: res.data,
          time: day
        })
        console.log('activtiyList', that.data.activityList)
        //
        db.collection('collect').where({
          activityId: that.data.activityList._id,
          userId: app.globalData.userId,
        }).get().then(res => {
          console.log('查询正确', res)
          if (res.data.length != 0) {
            console.log('查到了', res)
            that.setData({
              collectId: res.data[0]._id,
              isCollect: true,
              collectWord: "已收藏"
            })
          } else {
            console.log('未查到')
            that.setData({
              collectId: "",
              isCollect: false,
              collectWord: "未收藏"
            })
          }
        }).catch(err => {
          console.log('查询错误', err)
        })
        // 获取用户缓存数据
        wx.getStorage({
          key: 'userInfo',
          success: function (resp) {
            that.setData({
              userInfo: resp.data
            })
            wx.hideLoading();
          },
          fail() {
            console.log('获取用户信息失败')
            wx.hideLoading();
          }
        })
      },
      fail: function () {
        // 获取数据
        console.log('没有缓存进行获取')
        wx.cloud.callFunction({
          name: 'volunteer',
          data: {
            type: 'getActivity',
            articleid: that.data.articleid
          }
        }).then((resp) => {
          console.log('活动详情-获取数据', resp.result.list[0])
          wx.setStorageSync('getActivity_' + that.data.articleid, resp.result.list[0])
          console.log('活动详情-获取数据', resp.result.list[0])
          // 获取用户信息
          db.collection('user').where({
            name: resp.result.list[0].name
          }).get({
            success: res => {
              // 保存用户信息
              that.setData({
                userInfo: res.data[0]
              })
              // 用户信息设置缓存
              wx.setStorageSync('userInfo', that.data.userInfo)
              console.log('用户信息', that.data.userInfo)
              // 计算相差天数
              let day = 1
              if (resp.result.list[0].date != undefined) {
                let start = new Date().toISOString().substring(0, 10)
                let end = resp.result.list[0].date
                let start_num = new Date(start.replace(/-/g, "/"))
                let end_num = new Date(end.replace(/-/g, "/"))
                day = parseInt((end_num.getTime() - start_num.getTime()) / (1000 * 60 * 60 * 24))
              }
              console.log('相差天数', day)
              that.setData({
                activityList: resp.result.list[0],
                time: day
              })
              wx.hideLoading();
            },
            fail: err => {
              console.log('[数据库] [查询记录] 失败：');
              wx.hideLoading();
            }
          })
        }).catch((e) => {
          console.log('出错了', e);
          wx.hideLoading();
        });
      }
    })
  },

  call() { // 打电话
    let phone = this.data.userInfo.phone // 仅为示例，并非真实的电话号码
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 报名
  save() {
    // console.log('报名信息',this.data.signUserList)
    let activityList = this.data.activityList
    var that = this
    if (this.data.signUserList.length >= activityList.sumPeople) {
      wx.showToast({
        title: '报名人数已满',
        icon: 'error'
      })
    } else if (activityList.status == '进行中') {
      wx.showToast({
        title: '该活动正在进行',
        icon: 'error'
      })
    } else if (activityList.status == '已结束') {
      wx.showToast({
        title: '该活动已结束',
        icon: 'error'
      })
    } else {
      let userList = this.data.signUserList
      // console.log('userinfo',app.globalData.userinfo._id)
      // 如果已经报名 
      for (var i = 0; i < userList.length; i++) {
        // console.log('userinfo._id', app.globalData.userinfo._id)
        // console.log('userList_id', userList[i])
        if (app.globalData.userinfo._id == userList[i]._id) {
          wx.showToast({
            title: '请勿重复报名',
          })
          return;
        }
      }
      userList.push(app.globalData.userinfo.username)
      wx.cloud.callFunction({
        name: 'volunteer',
        data: {
          type: 'updatePeople',
          articleid: that.data.articleid,
          currentPeople: activityList.currentPeople + 1,
          userList: userList
        },
        success() {
          // user_activity 表更新
          db.collection('user_activity').add({
            data: {
              user_id: app.globalData.userinfo._id,
              activity_id: that.data.articleid,
              time: util.formatTime(new Date()),
              status: that.data.activityList.status
            }
          }).then(res => {
            wx.showToast({
              title: '报名成功',
              icon: 'success'
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 500)

          })

        }
      })
    }
  },
  cancel() {
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      })
    }, 500)
  },
  // 查看详细报名信息
  gotoSignMess: function () {
    // 当前要跳转到另一个界面，但是会保留现有界面
    console.log('跳转到xxx页面', this.data.signUserList)
    wx.setStorageSync("signUserList", this.data.signUserList)
    wx.navigateTo({
      url: `../signPeopleMess/index`
    })
  }
})